#include <algorithm>
#include <brpc/closure_guard.h>
#include <brpc/server.h>
#include <butil/logging.h>
#include <string>
#include "main.pb.h"

// 1.继承EchoService创建一个子类，实现rpc调用的业务功能
class EchoServiceImpl : public example::EchoService
{
public:
    EchoServiceImpl() {}
    ~EchoServiceImpl() {}
    void Echo(google::protobuf::RpcController* controller, const ::example::EchoRequest* request, 
              ::example::EchoResponse* response, ::google::protobuf::Closure* done)
    {
        brpc::ClosureGuard rpcGuard(done);      // Closure 封装成RAII, 避免忘记调用其run
        std::cout << "收到消息:" << request->message() << "\n";
        std::string respMsg = request->message();
        std::reverse(respMsg.begin(), respMsg.end());
        response->set_message(respMsg);
    }
};


int main()
{
    // 关闭brpc的默认日志输出
    logging::LoggingSettings settings;
    settings.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(settings);
    // 2.构建服务器 
    brpc::Server server;
    EchoServiceImpl echoService;
    // 3.向服务器新增echoService服务
    int ret = server.AddService(&echoService, brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);
    if(ret == -1) {
        std::cout << "添加Rpc服务失败\n";
        return 1;
    }
    // 4.启动服务器
    brpc::ServerOptions options;    // 服务器的配置项
    options.idle_timeout_sec = -1;  // 连接空闲的超时上限(-1表无限空闲)
    options.num_threads = 1;        // io线程数
    ret = server.Start(8080, &options);
    if(ret == -1) {
        std::cout << "服务器启动失败\n";
        return 1;
    }
    server.RunUntilAskedToQuit();   // 休眠等待运行结束
    return 0;
}

